package cn.stylefeng.roses.kernel.ca.server.modular.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.ca.api.enums.SsoLoginPageType;
import cn.stylefeng.roses.kernel.ca.api.exception.enums.CaServerExceptionEnum;
import cn.stylefeng.roses.kernel.ca.server.modular.manage.entity.SsoClient;
import cn.stylefeng.roses.kernel.ca.server.modular.manage.enums.SsoClientExceptionEnum;
import cn.stylefeng.roses.kernel.ca.server.modular.manage.mapper.SsoClientMapper;
import cn.stylefeng.roses.kernel.ca.server.modular.manage.pojo.request.SsoClientRequest;
import cn.stylefeng.roses.kernel.ca.server.modular.manage.service.SsoClientService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 单点登录客户端业务实现层
 *
 * @author fengshuonan
 * @since 2023/11/05 09:28
 */
@Service
public class SsoClientServiceImpl extends ServiceImpl<SsoClientMapper, SsoClient> implements SsoClientService {

    @Override
    public void add(SsoClientRequest ssoClientRequest) {

        // 如果是自定义登录界面，那么必须要有自定义登录界面的地址
        if (ssoClientRequest.getLoginPageType().equals(SsoLoginPageType.CUSTOM.getCode())) {
            String customLoginUrl = ssoClientRequest.getCustomLoginUrl();
            if (StrUtil.isBlank(customLoginUrl)) {
                throw new ServiceException(SsoClientExceptionEnum.CUSTOM_LOGIN_URL_EMPTY);
            }
        }

        SsoClient ssoClient = new SsoClient();
        BeanUtil.copyProperties(ssoClientRequest, ssoClient);

        if (ssoClient.getClientSort() == null) {
            ssoClient.setClientSort(new BigDecimal(100));
        }

        this.save(ssoClient);
    }

    @Override
    public void del(SsoClientRequest ssoClientRequest) {
        SsoClient ssoClient = this.querySsoClient(ssoClientRequest);
        this.removeById(ssoClient.getClientId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(SsoClientRequest ssoClientRequest) {
        this.removeByIds(ssoClientRequest.getBatchDeleteIdList());
    }

    @Override
    public void edit(SsoClientRequest ssoClientRequest) {

        // 如果是自定义登录界面，那么必须要有自定义登录界面的地址
        if (ssoClientRequest.getLoginPageType().equals(SsoLoginPageType.CUSTOM.getCode())) {
            String customLoginUrl = ssoClientRequest.getCustomLoginUrl();
            if (StrUtil.isBlank(customLoginUrl)) {
                throw new ServiceException(SsoClientExceptionEnum.CUSTOM_LOGIN_URL_EMPTY);
            }
        }

        SsoClient ssoClient = this.querySsoClient(ssoClientRequest);
        BeanUtil.copyProperties(ssoClientRequest, ssoClient);
        this.updateById(ssoClient);
    }

    @Override
    public SsoClient detail(SsoClientRequest ssoClientRequest) {
        return this.querySsoClient(ssoClientRequest);
    }

    @Override
    public PageResult<SsoClient> findPage(SsoClientRequest ssoClientRequest) {
        LambdaQueryWrapper<SsoClient> wrapper = createWrapper(ssoClientRequest);

        wrapper.select(SsoClient::getClientId, SsoClient::getClientName, SsoClient::getClientLogoFileId, SsoClient::getLoginPageType,
                SsoClient::getUnifiedLogoutFlag, SsoClient::getClientStatus,
                BaseEntity::getCreateTime);

        Page<SsoClient> pageList = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(pageList);
    }

    @Override
    public void updateStatus(SsoClientRequest ssoClientRequest) {
        LambdaUpdateWrapper<SsoClient> ssoClientLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        ssoClientLambdaUpdateWrapper.set(SsoClient::getClientStatus, ssoClientRequest.getClientStatus())
                .eq(SsoClient::getClientId, ssoClientRequest.getClientId());
        this.update(ssoClientLambdaUpdateWrapper);
    }

    @Override
    public List<SsoClient> findList(SsoClientRequest ssoClientRequest) {
        LambdaQueryWrapper<SsoClient> wrapper = this.createWrapper(ssoClientRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author fengshuonan
     * @since 2023/11/05 09:28
     */
    private SsoClient querySsoClient(SsoClientRequest ssoClientRequest) {
        SsoClient ssoClient = this.getById(ssoClientRequest.getClientId());
        if (ObjectUtil.isEmpty(ssoClient)) {
            throw new ServiceException(CaServerExceptionEnum.CLIENT_NOT_EXIST);
        }
        return ssoClient;
    }

    /**
     * 创建查询wrapper
     *
     * @author fengshuonan
     * @since 2023/11/05 09:28
     */
    private LambdaQueryWrapper<SsoClient> createWrapper(SsoClientRequest ssoClientRequest) {
        LambdaQueryWrapper<SsoClient> queryWrapper = new LambdaQueryWrapper<>();

        String searchText = ssoClientRequest.getSearchText();
        if (StrUtil.isNotBlank(searchText)) {
            queryWrapper.like(ObjectUtil.isNotEmpty(searchText), SsoClient::getClientName, searchText);
            queryWrapper.or().like(SsoClient::getCustomLoginUrl, searchText);
            queryWrapper.or().like(SsoClient::getSsoLogoutUrl, searchText);
            queryWrapper.or().like(SsoClient::getSsoCallbackUrl, searchText);
        }

        return queryWrapper;
    }

}
